"""
初始化任务数据库
"""
import json
import os
from datetime import datetime
from .models import Task
from .sqlalchemy_database import SQLAlchemyDatabaseManager

def init_task_db(db: SQLAlchemyDatabaseManager):
    """
    初始化任务数据表
    :param db: 数据库管理器实例
    """
    # 创建任务表
    db.create_table(Task)

    # 如果有现有数据，检查是否需要添加新列
    for column in Task.__table__.columns:
        try:
            db.execute(f"SELECT {column.name} FROM {Task.__tablename__} LIMIT 1")
        except Exception:
            # 列不存在，添加新列
            try:
                db.execute(f"ALTER TABLE {Task.__tablename__} ADD COLUMN {column.name} {column.type}")
                print(f"添加新列: {column.name} ({column.type})")
            except Exception as e:
                print(f"添加列失败 {column.name}: {str(e)}")

    # 导入任务数据
    data_file = os.path.join(os.path.dirname(__file__), "uudata", "task_data.json")
    if os.path.exists(data_file):
        with open(data_file, 'r', encoding='utf-8') as f:
            tasks = json.load(f)
            
        now = int(datetime.now().timestamp() * 1000)
        
        for task in tasks:
            try:
                # 设置默认值
                task.setdefault('status', 1)
                task.setdefault('update_price_auto', 0)
                task.setdefault('bought_num', 0)
                task.setdefault('buying_num', 0)
                task.setdefault('disabled', 0)
                task.setdefault('create_at', now)
                task.setdefault('update_at', now)
                
                # 处理JSON字段
                if 'tags' in task and not isinstance(task['tags'], str):
                    task['tags'] = json.dumps(task['tags'])
                if 'filter_conf' in task and not isinstance(task['filter_conf'], str):
                    task['filter_conf'] = json.dumps(task['filter_conf'])
                if 'update_price_conf' in task and not isinstance(task['update_price_conf'], str):
                    task['update_price_conf'] = json.dumps(task['update_price_conf'])
                    
                # 检查是否存在
                result = db.session.query(Task).filter_by(goods_id=task['goods_id']).first()
                
                # 移除id字段，让数据库自动生成
                if 'id' in task:
                    del task['id']
                
                if result:
                    # 更新现有数据
                    for key, value in task.items():
                        setattr(result, key, value)
                    db.session.add(result)
                else:
                    # 插入新数据
                    new_task = Task(**task)
                    db.session.add(new_task)
                    
            except Exception as e:
                db.session.rollback()
                print(f"导入任务失败: {str(e)}")
        db.session.commit()
        print(f"导入任务数据完成")

def init_task_table(db=None):
    """初始化任务表"""
    # 使用SQLAlchemyDatabaseManager的默认数据库路径
    if db is None:
        db = SQLAlchemyDatabaseManager()
    init_task_db(db)
    print("任务表初始化完成")

if __name__ == "__main__":
    init_task_table()
